/**
 * 业户综合报警分析
 */
$(function(){
	EnterpriseAnaAL.init();
});
var EnterpriseAnaAL = {
	pieChartData:[],
	totalSubsection:[],
	GlobalGpsCache1:[],
	GlobalGpsCache2:[],
	GlobalGpsCache3:[],
	GlobalGpsCache4:[],
	init: function(){
		var me = this;

		me.initQueryTime();
		me.initEvent();
		me.PieChart=me.initPieChart();
		me.BarChart=me.initBarChart();
		//me.loadTableTitle();
		me.queryTable();
		me.initEntList(0,"");
	},
	initEvent: function(){
		var me = this;
		$('#timeSelect').on('change',function(){
			me.pickTime();
		});
		$("#queryBtn").click(function(){
			me.queryTable();
    	});
		$("#exportExcel").click(function(){
			me.exportExcel();
		});
	},
	/**
	选择时间的输入框被选中时，创建datepicker控件
	根据设置不同dateFmt 格式，使空间支持选择日，周，月，季，年
	*/
	 createWdatePicker:function() {
	    var type = $("#timeSelect").val();
	    var me = this;
	    if (type == 1) {
	    	//按日
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy-MM-dd',
	           // onpicked : me.pickTime,
	            isShowWeek : false,
	            maxDate : '%y-%M-{%d-1}'
	        });
	    } else if (type == 2) {
	    	//按周
	    } else if (type == 3) {
	    	//按月
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy-MM',
	            //onpicked : me.pickTime,
	            isShowWeek : true,
	            maxDate : '%y-%M'
	        });
	    } else if (type == 4) {
	    	//按季
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy年MM季度',
	            isQuarter:true, 
	            isShowOK:false, 
	            disabledDates:['....-0[5-9]-..','....-1[0-2]-..'], 
	            //startDate:'{%y-1}-01-01' 
	            onpicked : function(){
	            	$('.navImg NavImgl').attr("style='display: none;'");
	            },
	            //isShowWeek : true,
	            maxDate : '%y-{%M/3-1}-%d'
	        });
	    } else if (type == 5) {
	    	//按年
	        WdatePicker({
	            readOnly : true,
	            dateFmt : 'yyyy年',
	           // onpicked : me.pickTime,
	            isShowWeek : true,
	            maxDate : '%y'
	        });
	    }

	},
	pickTime : function(){
	    var type = $("#timeSelect").val();
	    var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (type == 1) {//按日
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	    	if (dd.length == 1) {
		        dd = '0' + dd;
		    }
	        $("#inputDate").val(yyyy + '-' + mm + '-' + dd);
	    } else if (type == 2) {//按周
	    	$("#selectDate").hide();
	    	$("#selectWeek").show();
	    	$.ajax({
	    		type : 'post',
	    		url : appCtx + "base/report/PlatformAnalyzes/queryweek.html",
	    		cache : false,
	    		dataType : "JSON",
	    		success : function(data) {
	    			if(data!=null&&data!=''){
	    				$.each(data,function(entryIndex,entry) {
	    					$("#week").append("<option value='"+entry.value+"'>"+entry.text+"</option>");
	    				});	
	    			}
	    		}
	    	});
	    } else if (type == 3) {//按月
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	    	var month = parseInt(mm) ;
	    	if (dd<24) {
	    		month = month-1;
			}
	    	if (month < 10) {
	    		month = '0' + month;
		    }
	    	$("#inputDate").val(yyyy + '-' + month);
	    } else if (type == 4) {//按季
	        //计算季度的开始月份和结束月份
	    	$("#selectWeek").hide();
	    	$("#selectDate").show();
	        var quarter = parseInt((mm - 1) / 3) ;
	        $("#inputDate").val(yyyy + '年0' + quarter +'季度');
	    } else if (type == 5) {//按年
	    	$("#inputDate").val(yyyy + '年');
	    }
	},
    //初始化时间
    initQueryTime : function(){
    	$("#selectWeek").hide();
    	$("#selectDate").show();
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputDate").val(yyyy + '-' + mm + '-' + dd);
    },
    //初始化菜单
    reLoadMenu : function(enterprise_id,timeType,time,week){
    	$("#selectEnterprise").val(enterprise_id);
    	$("#timeSelect").val(timeType);
    	$("#inputDate").val(time);
    	$("#week").val(week);
    	var name = $("#selectVehicleSel").find("option:selected").text();
    	$("#select2-selectVehicleSel-container").text(name);
    	EnterpriseAnaAL.queryTable();
    },
    //处理轨迹数据
	handTrack1 : function(jsonData){
		var me = this;
    	var GlobalGridField = ['enterprise_name','vehicle_count','vehicle_access_count','vehicle_access_rate','vehicle_online_count','vehicle_online_rate'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < GlobalGridField.length; i++){
    		tmpValue = jsonData[GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:me.GlobalGpsCache1.length,data:tmpData};
    	this.GlobalGpsCache1.push(gridData); 
    },
	handTrack2 : function(jsonData){
		var me = this;
    	var GlobalGridField = ['enterprise_name','regularBus','touringCar','dangerCar'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < GlobalGridField.length; i++){
    		tmpValue = jsonData[GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:me.GlobalGpsCache2.length,data:tmpData};
    	this.GlobalGpsCache2.push(gridData); 
    },
	handTrack3 : function(jsonData){
		var me = this;
    	var GlobalGridField = ['enterprise_name','alarm_vehicle_count','vehicle_alarm_rate','alarm_count','alarm_processed','alarm_processed_rate','overspeed_count','avg_vehicle_speed_counts','tired_duration','avg_vehicle_tired_duration'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < GlobalGridField.length; i++){
    		tmpValue = jsonData[GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:me.GlobalGpsCache3.length,data:tmpData};
    	this.GlobalGpsCache3.push(gridData); 
    },
	handTrack4 : function(jsonData){
		var me = this;
    	var GlobalGridField = ['enterprise_name','exception_vehicle_count','exception_rate','speed_160_count','location_exception_count','gpstime_exception_count','head_exception_count','exception_contrast_rate'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < GlobalGridField.length; i++){
    		tmpValue = jsonData[GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:me.GlobalGpsCache4.length,data:tmpData};
    	this.GlobalGpsCache4.push(gridData); 
    },
	initSubDetail1:function(){
		var me = this;
		var wid =$("#width1").width();
		var height =$("#width1").height();
		// var wid =$("#objTable1").width();
		var widStr = 0.3*wid+","+0.14*wid+","+0.14*wid+","+0.14*wid+","+0.14*wid+","+(0.14*wid-16);
		var initOptions = {	// 表格配置
		           tableId:'objTable1',
		           header:'业户名称,车辆总数,入网数,入网率(%),上线数,上线率(%)',
		           colTypes:'ro,ro,ro,ro,ro,ro',
		           code :'enterprise_name,vehicle_count,vehicle_access_count,vehicle_access_rate,vehicle_online_count,vehicle_online_rate',
		           initWidths:widStr,
		           initWidthps:widStr,
		           align:'left,left,left,left,left,left',
		           sort:'no,no,no,no,no,no'
		    	 };
		me.myGrid1 = new dhtmlXGridObject(initOptions.tableId);
		me.myGrid1.setHeader(initOptions.header,null,["text-align:left;","text-align:left;","text-align:left;",
			"text-align:left;","text-align:left;","text-align:left;"]);//列标题
		me.myGrid1.setInitWidths(initOptions.initWidths);
		me.myGrid1.setColumnIds(initOptions.code);
		me.myGrid1.setColAlign(initOptions.align);//设置列数据的水平布局
		me.myGrid1.setColTypes(initOptions.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
		me.myGrid1.setColSorting(initOptions.sort);
		me.myGrid1.setSkin("dhx_skyblue");//指明使用什么皮肤
		me.myGrid1.enableAutoHeight(false,'auto',true);
		me.myGrid1.init();
		me.myGrid1.enablePreRendering(1000);
		me.myGrid1.enableSmartRendering(false);
        $("#objTable1").width(wid)
        $("#objTable1").height(height)
		me.myGrid1.attachEvent("onRowSelect",function(id,ind){
			me.queryBarChart(me.totalSubsection[id].enterprise_id);
    	 });
	},
	initSubDetail2:function(){
		var me = this;
        var wid =$("#width2").width();
        var height =$("#width2").height();
		var widStr = 0.19*wid+","+0.27*wid+","+0.27*wid+","+(0.27*wid-16);
		var initOptions = {	// 表格配置
		           tableId:'objTable2',
		           header:'业户名称,班线客运,旅游客运,危运车辆',
		           colTypes:'ro,ro,ro,ro',
		           code :'enterprise_name,regularBus,touringCar,dangerCar',
		           initWidths:widStr,
		           initWidthps:widStr,
		           align:'left,center,center,center',
		           sort:'no,no,no,no'
		    	 };
		me.myGrid2 = new dhtmlXGridObject(initOptions.tableId);
		me.myGrid2.setHeader(initOptions.header,null,["text-align:left;","text-align:center;","text-align:center;",
			"text-align:center;"]);//列标题
		me.myGrid2.setInitWidths(initOptions.initWidths);
		me.myGrid2.setColumnIds(initOptions.code);
		me.myGrid2.setColAlign(initOptions.align);//设置列数据的水平布局
		me.myGrid2.setColTypes(initOptions.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
		me.myGrid2.setColSorting(initOptions.sort);
		me.myGrid2.setSkin("dhx_skyblue");//指明使用什么皮肤
		me.myGrid2.enableAutoHeight(false,'auto',true);
		me.myGrid2.init();
		me.myGrid2.enablePreRendering(1000);
		me.myGrid2.enableSmartRendering(true);
        $("#objTable2").width(wid)
        $("#objTable2").height(height)
		me.myGrid2.attachEvent("onRowSelect",function(id,ind){
    	 });
	},
	initSubDetail3:function(){
		var me = this;
        var wid =$("#width3").width();
        var height =$("#width3").height();
		var widStr = 0.19*wid+","+0.08*wid+","+0.07*wid+","+0.07*wid+","+0.07*wid+","+0.07*wid+","+0.1*wid+","+0.1*wid+","+0.12*wid+","+(0.13*wid-16);
		var initOptions = {	// 表格配置
		           tableId:'objTable3',
		           header:'业户名称,报警车辆数,报警率(%),报警条数,处理条数,处警率(%),超速报警条数,平均超速次数(次),疲劳驾驶时长(分钟),平均疲劳驾驶时长(分钟)',
		           colTypes:'ro,ro,ro,ro,ro,ro,ro,ro,ro,ro',
		           code :'enterprise_name,alarm_vehicle_count,vehicle_alarm_rate,alarm_count,alarm_processed,alarm_processed_rate,overspeed_count,avg_vehicle_speed_counts,tired_duration,avg_vehicle_tired_duration',
		           initWidths:widStr,
		           initWidthps:widStr,
		           align:'left,left,left,left,left,left,left,left,left,left',
		           sort:'no,no,no,no,no,no,no,no,no,no'
		    	 };
		me.myGrid3 = new dhtmlXGridObject(initOptions.tableId);
		me.myGrid3.setHeader(initOptions.header,null,["text-align:left;","text-align:left;","text-align:left;","text-align:left;",
			"text-align:left;","text-align:left;","text-align:left;","text-align:left;","text-align:left;","text-align:left;"]);//列标题
		me.myGrid3.setInitWidths(initOptions.initWidths);
		me.myGrid3.setColumnIds(initOptions.code);
		me.myGrid3.setColAlign(initOptions.align);//设置列数据的水平布局
		me.myGrid3.setColTypes(initOptions.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
		me.myGrid3.setColSorting(initOptions.sort);
		me.myGrid3.setSkin("dhx_skyblue");//指明使用什么皮肤
		me.myGrid3.enableAutoHeight(false,'auto',true);
		me.myGrid3.init();
		me.myGrid3.enablePreRendering(1000);
		me.myGrid3.enableSmartRendering(true);
        $("#objTable3").width(wid)
        $("#objTable3").height(height)
		me.myGrid3.attachEvent("onRowSelect",function(id,ind){
    	 });
	},
	initSubDetail4:function(){
		var me = this;
        var wid =$("#width4").width();
        var height =$("#width4").height();
		var widStr = 0.20*wid+","+0.1*wid+","+0.1*wid+","+0.1*wid+","+0.11*wid+","+0.12*wid+","+0.09*wid+","+(0.18*wid-16);
		var initOptions = {	// 表格配置
		           tableId:'objTable4',
		           header:'业户名称,异常车辆数,异常率(%),速度>160,经纬度异常,定位时间异常,方向异常,异常数据比率(%)',
		           colTypes:'ro,ro,ro,ro,ro,ro,ro,ro',
		           code :'enterprise_name,exception_vehicle_count,exception_rate,speed_160_count,location_exception_count,gpstime_exception_count,head_exception_count,exception_contrast_rate',
		           initWidths:widStr,
		           initWidthps:widStr,
		           align:'left,left,left,left,left,left,left,left',
		           sort:'no,no,no,no,no,no,no,no'
		    	 };
		me.myGrid4 = new dhtmlXGridObject(initOptions.tableId);
		me.myGrid4.setHeader(initOptions.header,null,["text-align:left;","text-align:left;","text-align:left;",
			"text-align:left;","text-align:left;","text-align:left;","text-align:left;","text-align:left;"]);//列标题
		me.myGrid4.setInitWidths(initOptions.initWidths);
		me.myGrid4.setColumnIds(initOptions.code);
		me.myGrid4.setColAlign(initOptions.align);//设置列数据的水平布局
		me.myGrid4.setColTypes(initOptions.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
		me.myGrid4.setColSorting(initOptions.sort);
		me.myGrid4.setSkin("dhx_skyblue");//指明使用什么皮肤
		me.myGrid4.enableAutoHeight(false,'auto',true);
		me.myGrid4.init();
		me.myGrid4.enablePreRendering(1000);
		me.myGrid4.enableSmartRendering(true);
        $("#objTable4").width(wid)
        $("#objTable4").height(height)
		me.myGrid4.attachEvent("onRowSelect",function(id,ind){
			me.showpieChart(me.pieChartData[id]);
    	 });
	},
	
    
	
	initPieChart: function(){
		var me = this;
		option = {
				/*			    title : {
							        text: '异常统计分析',
							        subtext: '异常分析',
							        x:'center'
							    },*/
							    grid:{
							    	top:35,
							    	bottom:0,
							    	right:0,
							    },
							    tooltip : {
							        trigger: 'item',
							        formatter: "{a} <br/>{b} : {c} ({d}%)"
							    },
							    legend: {
							        orient: 'vertical',
							        left: 'left',
							        data: []
							    },
							    series : [
							        {
							            name: '异常统计',
							            type: 'pie',
							            radius: ['45%', '75%'],
							            center: ['50%', '50%'],
							            avoidLabelOverlap: true,
							            label: {
							                normal: {
							                    show: true,
							                    formatter: '{b}',
							                    backgroundColor: '#eee',
							                    borderColor: '#aaa',
							                    borderWidth: 1,
							                    borderRadius: 4,
							                },
							                emphasis: {
							                    show: true,
							                    position:'inside',
							                    textStyle: {
							                        fontSize: '15',
							                        fontWeight: 'bold'
							                    }
							                }
							            },
							            labelLine: {
							                normal: {
							                    show: true,
							                },
							                
							            },
							            data:[]
							        }
							    ],
								 color: ['rgb(249,124,37)','rgb(74,178,191)','rgb(134,218,179)','rgb(97,160,168)']
							};
		
		 var PieChart = echarts.init(document.getElementById('pieChart'));
		 PieChart.setOption(option);
         window.onresize = PieChart.resize;
         return {
         	refash : function(option){
         		PieChart.setOption(option);
         	},
         	option : option,
         	pieChartDom : PieChart
         };
	},
	
	initBarChart: function(){
		var me = this;
		option = {
			    tooltip: {
			        trigger: 'axis',
			        formatter: '{b0}<br />{a0}: {c0}%',
			        axisPointer: {
			            type: 'cross',
			            crossStyle: {
			                color: '#999'
			            }
			        }
			    },
			    legend: {
			        data:['入网率','上线率'],
		        	top:'0px'
			    },
			    grid: {
			        left: '40px',
			        top:'30px',
			        right: '10px',
			        bottom:"10%",
//			        containLabel: true
			    },
			    xAxis: [
			        {
			            type: 'category',
			            data: [],
			            axisPointer: {
			                type: 'shadow'
			            }
			        }
			    ],
			    yAxis: [
			        {
			            type: 'value',
			            min: 0,
			            max: 100,
			            interval: 20,
			            axisLabel: {
			                formatter: '{value} %'
			            }
			        },
			    ],
			    series: [
			        {
			            name:'入网率',
			            type:'bar',
			            barMaxWidth: '35px',
			            itemStyle: {normal: {color:'#27727b'}},
			            data:[]
			        },
			        {
			            name:'上线率',
			            type:'bar',
			            barMaxWidth: '35px',
			            itemStyle: {normal: {color:'#e87c25'}},
			            data:[]
			        }
			    ]
			};
	        var mydoubleChart = echarts.init(document.getElementById('doubleBarChart'));
	        mydoubleChart.setOption(option);
	        window.onresize = mydoubleChart.resize;
	        return {
	        	refash : function(option){
	        		mydoubleChart.setOption(option);
	        	},
	        	option : option,
	        	doubleBarChart : mydoubleChart
	        };        
		},
	initEntList:function(enterprise_id,enterprise_name){
		var me = this;
		$("#selectEnterprise").select2({
	        theme: "default",
	        allowClear: true,
	        placeholder: "请选择业户",
	        ajax:{
	            url:appCtx + "base/report/enterpriseAnalyzes/queryEnterprise.html",
	            dataType:"json",
	            delay:250,
	            data:function(params){
	                return {
	                	enterprise_name: params.term,
	                };
	            },
	            cache:true,
	            processResults: function (res) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部业户"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
							var option = {"id":obj.id, "text":obj.enterprise_name};
    	                    options.push(option);
	    				});
    	                return {
    	                	results: options,
    	                    pagination: {
    	                        more:false
    	                    }
    	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	    });
		if (enterprise_id!=0) {
			$("#selectEnterprise").html("<option value='" + enterprise_id + "'>" + enterprise_name + "</option>").trigger("change");
		}
	},

    queryTable:function(){
    	var me = this;
    	var enterprise_id = $.trim($("#selectEnterprise").val());
    	var inputTime = "";
    	var timeType = $("#timeSelect").val();
    	var time = $("#inputDate").val();
    	var week = $("#week").val();
    	if (timeType==1) {
			inputTime = time.substring(2,4)+time.substring(5,7)+time.substring(8,10);
		}else if(timeType==2) {
    		inputTime = week;
		}else if(timeType==3) {
			inputTime = time.substring(2,4)+time.substring(5,7);
		}else if(timeType==4) {
			inputTime = time.substring(2,4)+time.substring(5,7);
		}else if(timeType==5) {
			inputTime = time.substring(2,4);
		}
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryEnterpriseSwap1.html",
    		type:"post",
    		async : true,
    		cache : false,
    		data:{
    			timeType:timeType,
    			inputTime:inputTime,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(data){
            	me.GlobalGpsCache1 = [];
                if(data && data.length > 0){
                	var rowLen = data.length; 
                	for(var i=0;i<rowLen;i++){
                		var row = data[i];
                		me.handTrack1(row);
                	}
                	 var GlobalGpsCacheData1 = {
                			rows: me.GlobalGpsCache1
                	};
                	console.log(GlobalGpsCacheData1)
                	me.myGrid1.parse(GlobalGpsCacheData1,"json");
                	me.queryBarChart(data[0].enterprise_id);
                	me.totalSubsection = data;
                }else{
                	//$("#objTable1 tr:not(:first)").remove(); 
                	//$("#objTable1 tr:eq(0)").after("<tr><td colspan='6'>无数据</td></tr>"); 
                	window.parent.global.ajaxLoading.pop("查询无结果",false,1500);
                }
            }
    	});
		me.initSubDetail1();
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryEnterpriseSwap2.html",
    		type:"post",
    		async : true,
    		cache : false,
    		data:{
    			timeType:timeType,
    			inputTime:inputTime,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(data){
            	me.GlobalGpsCache2 = [];
            	totalSubsection2=[];
            	//debugger;
                if(data && data.length > 0){
                	totalSubsection2=JSON.stringify(data);
                	totalSubsection2=JSON.parse(totalSubsection2);
                	var rowLen = data.length;
                	var row = {};
                	row["enterprise_name"]="";
                	row["regularBus"] = "<span class='spstyle1'>车辆总数</span>|"+
    				"<span class='spstyle2'>入网数(率)</span>|"+
    				"<span class='spstyle3'>上线数(率)</span>";
    				row["touringCar"] = "<span class='spstyle1'>车辆总数</span>|"+
    				"<span class='spstyle2'>入网数(率)</span>|"+
    				"<span class='spstyle3'>上线数(率)</span>";
					row["dangerCar"] = "<span class='spstyle1'>车辆总数</span>|"+
    				"<span class='spstyle2'>入网数(率)</span>|"+
    				"<span class='spstyle3'>上线数(率)</span>";
            		me.handTrack2(row);
                	for(var i=0;i<rowLen;i++){
                		var row = data[i];
                		var regular = row.regularBus.split(",");
        				row.regularBus = "<span class='spstyle1'>"+parseInt(regular[0])+"</span>|"+
        				"<span class='spstyle2'>"+regular[1]+"</span>|"+
        				"<span class='spstyle3'>"+regular[2]+"</span>";
        				var touring = row.touringCar.split(",");
        				row.touringCar = "<span class='spstyle1'>"+parseInt(touring[0])+"</span>|"+
        				"<span class='spstyle2'>"+touring[1]+"</span>|"+
        				"<span class='spstyle3'>"+touring[2]+"</span>";
    					var danger = row.dangerCar.split(",");
    					row.dangerCar = "<span class='spstyle1'>"+parseInt(danger[0])+"</span>|"+
        				"<span class='spstyle2'>"+danger[1]+"</span>|"+
        				"<span class='spstyle3'>"+danger[2]+"</span>";
                		me.handTrack2(row);
                	}
                	GlobalGpsCacheData2 = {
                			rows: me.GlobalGpsCache2
                	};
                	me.myGrid2.parse(GlobalGpsCacheData2,"json");
                }else{
                	//$("#objTable2 tr:eq(0)").after("<tr><td colspan='4'>无数据</td></tr>"); 
                	window.parent.global.ajaxLoading.pop("查询无结果",false,1500);
                }
            }
    	});
    	me.initSubDetail2();
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryEnterpriseSwap3.html",
    		type:"post",
    		async : true,
    		cache : false,
    		data:{
    			timeType:timeType,
    			inputTime:inputTime,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(data){
            	me.GlobalGpsCache3 = [];
                if(data && data.length > 0){
                	var rowLen = data.length; 
                	for(var i=0;i<rowLen;i++){
                		var row = data[i];
                		row.vehicle_alarm_rate = row.vehicle_online_count>0?Math.round(((row.alarm_vehicle_count/row.vehicle_online_count)*100)*Math.pow(10,2))/Math.pow(10,2) :0;
                		row.alarm_processed_rate = row.alarm_count >0 ?Math.round(((row.alarm_processed/row.alarm_count)*100)*Math.pow(10,2))/Math.pow(10,2) :0;
                		row.tired_duration = parseInt(row.tired_duration/60);
                		row.avg_vehicle_tired_duration = parseInt(row.avg_vehicle_tired_duration/60);
                		me.handTrack3(row);
                	}
                	GlobalGpsCacheData3 = {
                			rows: me.GlobalGpsCache3
                	};
                	me.myGrid3.parse(GlobalGpsCacheData3,"json");
                }else{
                	//$("#objTable3 tr:eq(0)").after("<tr><td colspan='10'>无数据</td></tr>"); 
                	window.parent.global.ajaxLoading.pop("查询无结果",false,1500);
                }
            }
    	});
    	me.initSubDetail3();
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryEnterpriseSwap4.html",
    		type:"post",
    		async : true,
			cache : false,
    		data:{
    			timeType:timeType,
    			inputTime:inputTime,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(data){
            	me.GlobalGpsCache4 = [];
                if(data && data.length > 0){
                	var rowLen = data.length; 
                	for(var i=0;i<rowLen;i++){
                		var row = data[i];
        				row.exception_contrast_rate = (row.track_normal+row.exception_track_count)>0?
        						Math.round(((row.exception_track_count/(row.track_normal+row.exception_track_count))*100)*Math.pow(10,2))/Math.pow(10,2):0;
        				row.exception_rate = row.vehicle_online_count>0?
        						Math.round((row.exception_vehicle_count*100.0/row.vehicle_online_count)*Math.pow(10,2))/Math.pow(10,2):0;
                		me.handTrack4(row);
                	}
                	GlobalGpsCacheData4 = {
                			rows: me.GlobalGpsCache4
                	};
                	me.myGrid4.parse(GlobalGpsCacheData4,"json");
                	me.showpieChart(data[0]);
                	me.pieChartData = data;
                }else{
                	 me.showpieChart('');
                	//$("#objTable4 tr:eq(0)").after("<tr><td colspan='8'>无数据</td></tr>"); 
                	 window.parent.global.ajaxLoading.pop("查询无结果",false,1500);
                }
            }
    	});
    	me.initSubDetail4();
    },
    queryBarChart : function(enterprise_id){
    	var me = this;
    	var inputTime = "";
    	var timeType = $("#timeSelect").val();
    	var time = $("#inputDate").val();
    	var week = $("#week").val();
    	if (timeType==1) {
			inputTime = time.substring(2,4)+time.substring(5,7)+time.substring(8,10);
		}else if(timeType==2) {
    		inputTime = week;
		}else if(timeType==3) {
			inputTime = time;
		}else if(timeType==4) {
			inputTime = time.substring(2,4)+time.substring(5,7);
		}else if(timeType==5) {
			inputTime = time.substring(2,4);
		}
    	$.ajax({
    		url:appCtx+"base/report/enterpriseAnalyzes/queryBarChart.html",
    		type:"post",
    		cache : false,
    		data:{
    			inputTime:inputTime,
    			timeType:timeType,
    			enterprise_id:enterprise_id
    		},
    		dataType:"json",
    		success:function(datas){
    			var xis = new Array();
    			var series1 = new  Array();
    			var series2 = new  Array();
    			var enterprise=null;
    			$.each(datas,function(index,ent){
    				var MonDay = new Date(ent.analyse_date);
    	    		var afterDate = new Date(MonDay+86400000*1); //周二
    			    var yyyy = MonDay.getFullYear(), mm = (MonDay.getMonth() + 1).toString(), dd = MonDay.getDate().toString();
    			    if (mm.length == 1) {
    			        mm = '0' + mm;
    			    }
    			    if (dd.length == 1) {
    			        dd = '0' + dd;
    			    }
    				xis.push(yyyy+"-"+mm+"-"+dd);
    				series1.push(Math.round((ent.vehicle_access_rate)*Math.pow(10,2))/Math.pow(10,2));
    				series2.push(Math.round((ent.vehicle_online_rate)*Math.pow(10,2))/Math.pow(10,2));
    			});
    			var options = me.BarChart.option;
    			options.xAxis[0].data=xis;
    			options.series[0].data=series1;
    			options.series[1].data=series2;
    			me.BarChart.refash(options);
    		}
    	})
    },
    showpieChart : function(obj){
    	var me = EnterpriseAnaAL;
    	var option = me.PieChart.option;
    	var datas =new Array()
    	$("#noData").remove();
    	if(obj!=null&&obj!=''&&obj!=undefined){
    		if(obj.gpstime_exception_count!=0||obj.location_exception_count!=0||obj.head_exception_count!=0||obj.speed_160_count!=0){
    			valueArr = [obj.gpstime_exception_count,obj.location_exception_count,obj.head_exception_count,obj.speed_160_count];
    			var nameArr = ['定位时间异常','经纬度异常','方向异常','速度>160'];
    			for(var i=0;i<nameArr.length;i++){
    				var map =new Object();
    				map.name=nameArr[i];
    				map.value=valueArr[i];
    				datas.push(map);
    			}
    			option.legend.data=nameArr;
    			option.series[0].data=datas;// [10, 52, 200, 334, 390, 330, 220];
    			me.PieChart.refash(option);
    		}else{
    			global.noData("#pieChart");	
    		}

    	}else{
    		global.noData("#pieChart");	
    	}
    },
    exportExcel : function(){
    	var me = this;
    	if(me.GlobalGpsCache1.length==0&&totalSubsection2.length==0&&me.GlobalGpsCache3.length==0&&me.GlobalGpsCache4.length==0){
    		window.parent.global.ajaxLoading.pop("无数据导出",false,2000);
			return;
		}
    	window.parent.global.ajaxLoading.pop("正在导出,请稍后.....", true, 2000);
    	//图片
    	var imageUrl2 = me.PieChart.pieChartDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
		}); 
		 
		 var imageUrl3 = me.BarChart.doubleBarChart.getDataURL({
				type: 'png',
			    pixelRatio: 1
		}); 
	 	var imgsrcList=new Array();
	 	imgsrcList.push(imageUrl2);
	 	imgsrcList.push(imageUrl3);
	 	var imgsrc= $.toJSON(imgsrcList);
	 	var tableDataStrList=new Array();
		var tableDataStr1="";
		var tableDataStr2="--#车辆总数|入网数(率)|上线数(率)#车辆总数|入网数(率)|上线数(率)#车辆总数|入网数(率)|上线数(率)&";
		var tableDataStr3="";
		var tableDataStr4="";
		for(var i=0;i<me.GlobalGpsCache1.length;i++){
			var arrValue = me.GlobalGpsCache1[i].data;
			tableDataStr1 += arrValue[0]+"#"+arrValue[1]+"#"+arrValue[2]+
			"#"+arrValue[3]+"#"+arrValue[4]+"#"+arrValue[5]+"&";
		}
		for(var i=0;i<totalSubsection2.length;i++){
			var arrValue = totalSubsection2[i];
    		var regular = arrValue.regularBus.split(",");
			var touring = arrValue.touringCar.split(",");
			var danger = arrValue.dangerCar.split(",");
			tableDataStr2 += arrValue.enterprise_name+"#"+parseInt(regular[0])+"|"+regular[1]+"|"+regular[2]+
			"#"+parseInt(touring[0])+"|"+touring[1]+"|"+touring[2]+"#"+parseInt(danger[0])+"|"+danger[1]+"|"+danger[2]+"&";
		}
		for(var i=0;i<me.GlobalGpsCache3.length;i++){
			var arrValue = me.GlobalGpsCache3[i].data;
			tableDataStr3 += arrValue[0]+"#"+arrValue[1]+"#"+arrValue[2]+"#"+arrValue[3]+"#"+arrValue[4]+"#"+arrValue[5]+
			"#"+arrValue[6]+"#"+arrValue[7]+"#"+arrValue[8]+"#"+arrValue[9]+"&";
		}
		for(var i=0;i<me.GlobalGpsCache4.length;i++){
			var arrValue = me.GlobalGpsCache4[i].data;
			tableDataStr4 += arrValue[0]+"#"+arrValue[1]+"#"+arrValue[2]+
			"#"+arrValue[3]+"#"+arrValue[4]+"#"+arrValue[5]+"#"+arrValue[6]+"#"+arrValue[7]+"&";
		}
		tableDataStrList.push(tableDataStr1);
		tableDataStrList.push(tableDataStr2);
		tableDataStrList.push(tableDataStr3);
		tableDataStrList.push(tableDataStr4);
		var tableDataStr= $.toJSON(tableDataStrList);
		var tableDataTtilesList=new Array();
		var tableDataTtiles1="业户名称,车辆总数,入网数,入网率(%),上线数,上线率(%)";
		var tableDataTtiles2="业户名称,班线客运,旅游客运,危运车辆";
		var tableDataTtiles3="业户名称,报警车辆数,报警率(%),报警条数,处理条数,处警率(%),超速报警条数,平均超速次数(次),疲劳驾驶时长(分钟),平均疲劳驾驶时长(分钟)";
		var tableDataTtiles4="业户名称,异常车辆数,异常率(%),速度>160,经纬度异常,定位时间异常,方向异常,异常数据比率(%)";
		tableDataTtilesList.push(tableDataTtiles1);
		tableDataTtilesList.push(tableDataTtiles2);
		tableDataTtilesList.push(tableDataTtiles3);
		tableDataTtilesList.push(tableDataTtiles4);
		var tableDataTtiles= $.toJSON(tableDataTtilesList);
		var sheetNames=["业户车辆统计","业户行业统计","业户报警统计","业户异常统计"];
		var sheetList = $.toJSON(sheetNames);
		var param =  {
				tableDataStr:tableDataStr,
				tableDataTtiles:tableDataTtiles,
				sheetNames:sheetList, 
				title:"业户分析统计表",
				imgsrc:imgsrc
		};
    	post(appCtx+"base/report/enterpriseAnalyzes/export.html",param);
    },
};

 
/**
    控件返回的时间对象转换成字符串输出
    控件的时间对象有y,M,d,H,m,s属性，分别返回年，月，日，时，分，秒
*/
function dateToString(date) {
    var strdate = "";
    strdate = strdate + date.y + "-";
    var M = date.M >= 10 ? date.M : ("0" + date.M);
    strdate = strdate + M;
    var d = date.d >= 10 ? date.d : ("0" + date.d);
    strdate = strdate + "-" + d;
    return strdate;
};